package com.example.baiduapi.Chart.Picther;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.*;
import java.time.LocalDate;

public class ImgLoader {
    //main方法
    public static void main(String[] args) throws Exception {
        // 输出当前电脑IP地址
        load("https://wenxin.baidu.com/younger/file/ERNIE-ViLG/b370350891b2c8a4a1f3b73aa03128c4ex","110");
    }
    public static void load(String imageUrl,String userID) throws Exception {
       // imageUrl = "https://wenxin.baidu.com/younger/file/ERNIE-ViLG/b370350891b2c8a4a1f3b73aa03128c4ex"; // 图片的URL地址
        String LoaderUrl = "0"+userID+"\\"+ LocalDate.now()+"\\"+InetAddress.getLocalHost()+"||"+System.currentTimeMillis();
/*        String savePath = "D:\\IDEADEMO\\BaiDuApi\\Test\\BaiDuAPI\\src\\main\\resources\\static\\image"+LoaderUrl;
       */ String savePath = "C:\\Users\\Administrator\\Pictures\\45966123_fb2facfb7fb48d5d6b876efbed3e3dcc.jpg"; // 保存图片的本地路径
        try {
            URL url = new URL(imageUrl);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("GET");

            int responseCode = connection.getResponseCode();
            if (responseCode == HttpURLConnection.HTTP_OK) {
                InputStream inputStream = connection.getInputStream();

                File file = new File(savePath);
                if (!file.exists()) {
                    file.createNewFile();
                }

                FileOutputStream outputStream = new FileOutputStream(file);
                byte[] buffer = new byte[4096];
                int bytesRead;
                while ((bytesRead = inputStream.read(buffer)) != -1) {
                    outputStream.write(buffer, 0, bytesRead);
                }

                outputStream.close();
                inputStream.close();

                System.out.println("图片下载成功！");
            } else {
                System.out.println("服务器返回错误：" + responseCode);
            }

            connection.disconnect();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
